package com.aoxon.cargo.keydown;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.view.KeyEvent;

import com.aoxon.cargo.util.ToastUtil;

/**
 * 退出应用程序的按键处理
 * 
 * @author ZZJ
 */
public class ExitApplication {

    private static long    exitTime = 0;
    private Activity       activity = null;
    private static boolean isExit   = false;

    public ExitApplication(Activity activity) {
        this.activity = activity;
    }

    /**
     * 系统按键事件的处理
     * 
     * @param keyCode
     * @param event
     * @return
     */
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            back2Exit();
        }
        return true;
    }

    private void back2Exit() {
        if (isExit == false) {
            isExit = true;
            Timer tExit = new Timer();
            ToastUtil.show(activity, "再按一次退出程序");
            tExit.schedule(new TimerTask() {

                @Override
                public void run() {
                    isExit = false;
                }
            }, 2000);
        } else {
            ToastUtil.cancel();
            activity.finish();
        }

    }
}
